<template>
  <div class="homework-detail-container">
    <el-card class="homework-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h2>{{ homework.title }}</h2>
          <div class="status-tags">
            <el-tag :type="getStatusType(homework.status)">
              {{ getStatusText(homework.status) }}
            </el-tag>
            <el-tag type="info" effect="plain">
              截止日期：{{ formatDate(homework.endTime) }}
            </el-tag>
          </div>
        </div>
      </template>
      
      <div class="homework-content">
        <div class="section-title">作业内容</div>
        <div class="content" v-html="homework.content"></div>
        
        <div v-if="homework.attachmentUrl" class="attachment-section">
          <div class="section-title">作业附件</div>
          <el-button type="primary" link @click="downloadAttachment(homework.attachmentUrl)">
            <el-icon><Download /></el-icon>
            下载附件
          </el-button>
        </div>
      </div>
      
      <el-divider />
      
      <!-- 未提交状态且未过期 -->
      <div v-if="homework.status === 0 && !isHomeworkExpired(homework.endTime)" class="submission-section">
        <div class="section-title">提交作业</div>
        <el-form ref="formRef" :model="submission" :rules="rules" label-width="80px">
          <el-form-item label="内容" prop="content">
            <el-input 
              v-model="submission.content" 
              type="textarea" 
              :rows="6"
              placeholder="请输入作业内容..."
            />
          </el-form-item>
          
          <el-form-item label="附件">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              :limit="1"
            >
              <el-button type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  允许上传PDF, Word, Excel, PPT等格式文件，大小不超过10MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSubmitHomework">提交作业</el-button>
            <el-button @click="goBack">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 已提交但未批改 -->
      <div v-else-if="homework.status === 1" class="submission-section">
        <div class="section-title">你的提交</div>
        <div class="submission-info">
          <div class="submission-time">
            提交时间：{{ formatDate(submission.submitTime) }}
          </div>
          
          <div class="submission-content">
            <div class="section-subtitle">提交内容</div>
            <div v-html="submission.content"></div>
          </div>
          
          <div v-if="submission.attachmentUrl" class="submission-attachment">
            <div class="section-subtitle">提交的附件</div>
            <el-button type="primary" link @click="downloadAttachment(submission.attachmentUrl)">
              <el-icon><Download /></el-icon>
              查看附件
            </el-button>
          </div>
          
          <div class="submission-actions" v-if="!isHomeworkExpired(homework.endTime)">
            <el-button type="primary" @click="editSubmission">修改提交</el-button>
          </div>
        </div>
      </div>
      
      <!-- 已批改 -->
      <div v-else-if="homework.status === 2" class="submission-section">
        <div class="section-title">你的提交</div>
        <div class="submission-info">
          <div class="submission-time">
            提交时间：{{ formatDate(submission.submitTime) }}
          </div>
          
          <div class="submission-content">
            <div class="section-subtitle">提交内容</div>
            <div v-html="submission.content"></div>
          </div>
          
          <div v-if="submission.attachmentUrl" class="submission-attachment">
            <div class="section-subtitle">提交的附件</div>
            <el-button type="primary" link @click="downloadAttachment(submission.attachmentUrl)">
              <el-icon><Download /></el-icon>
              查看附件
            </el-button>
          </div>
        </div>
        
        <el-divider />
        
        <div class="feedback-section">
          <div class="section-title">教师评价</div>
          <div class="feedback-info">
            <div class="score">
              <div class="score-label">得分</div>
              <div class="score-value">{{ submission.score }}</div>
            </div>
            
            <div v-if="submission.feedback" class="feedback-comment">
              <div class="section-subtitle">评语</div>
              <div v-html="submission.feedback"></div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 未提交且已过期 -->
      <div v-else-if="homework.status === 0 && isHomeworkExpired(homework.endTime)" class="submission-section">
        <el-empty description="作业已过截止日期，无法提交" />
      </div>
      
      <div class="action-buttons">
        <el-button @click="goBack">返回列表</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import { formatDate } from '../../utils/format'
import { getHomeworkDetail, submitHomework, getStudentHomeworkSubmission } from '@/api/homework'
import { useUserStore } from '@/store/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const homeworkId = route.params.id
const isEdit = route.query.edit === 'true'

const loading = ref(true)
const homework = ref({})
const submission = reactive({
  homeworkId: homeworkId,
  studentId: '',
  content: '',
  attachmentUrl: '',
  submitTime: '',
  score: 0,
  feedback: ''
})

const formRef = ref(null)
const rules = {
  content: [
    { required: true, message: '请输入作业内容', trigger: 'blur' },
    { min: 5, message: '内容至少5个字符', trigger: 'blur' }
  ]
}

// 上传相关
const uploadUrl = `${import.meta.env.VITE_API_BASE_URL || ''}/api/file/submission`
const uploadHeaders = {}

// 初始化
onMounted(async () => {
  submission.studentId = userStore.userId
  await fetchHomeworkDetail()
  if (homework.value.status > 0) {
    await fetchSubmissionDetail()
  }
  loading.value = false
})

// 获取作业详情
const fetchHomeworkDetail = async () => {
  try {
    const res = await getHomeworkDetail(homeworkId)
    if (res.code === 200) {
      homework.value = res.data
    } else {
      ElMessage.error('获取作业详情失败')
    }
  } catch (error) {
    console.error('获取作业详情失败', error)
    ElMessage.error('获取作业详情失败')
  }
}

// 获取提交详情
const fetchSubmissionDetail = async () => {
  try {
    const res = await getStudentHomeworkSubmission(userStore.userId, homeworkId)
    if (res.code === 200) {
      Object.assign(submission, res.data)
    }
  } catch (error) {
    console.error('获取提交详情失败', error)
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'danger',
    1: 'warning',
    2: 'success'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未提交',
    1: '已提交',
    2: '已批改'
  }
  return statusMap[status] || '未知'
}

// 判断作业是否已过期
const isHomeworkExpired = (endTime) => {
  return new Date(endTime) < new Date()
}

// 提交作业
const handleSubmitHomework = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      loading.value = true
      const res = await submitHomework({
        homeworkId: homework.value.id,
        studentId: userStore.userId,
        content: submission.content,
        attachmentUrl: submission.attachmentUrl
      })
      
      if (res.code === 200) {
        ElMessage.success('作业提交成功')
        router.push('/student/homework-list')
      } else {
        ElMessage.error(res.message || '提交失败')
      }
    } catch (error) {
      console.error('提交作业失败', error)
      ElMessage.error('提交作业失败')
    } finally {
      loading.value = false
    }
  })
}

// 编辑提交
const editSubmission = () => {
  router.push(`/student/homework-submit/${homeworkId}?edit=true`)
}

// 上传成功
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    submission.attachmentUrl = response.data
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error('文件上传失败')
  }
}

// 上传失败
const handleUploadError = () => {
  ElMessage.error('文件上传失败')
}

// 上传前检查
const beforeUpload = (file) => {
  // 检查文件大小，限制为10MB
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB')
    return false
  }
  return true
}

// 下载附件
const downloadAttachment = (url) => {
  if (!url) return
  
  // 使用完整的URL
  const fullUrl = url.startsWith('http') ? url : `${import.meta.env.VITE_API_BASE_URL}${url}`
  
  // 创建临时链接下载
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = fullUrl
  link.setAttribute('download', url.split('/').pop() || '附件')
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 返回列表
const goBack = () => {
  router.push('/student/homework')
}
</script>

<style scoped>
.homework-detail-container {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
}

.homework-card {
  width: 100%;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5rem;
}

.status-tags {
  display: flex;
  gap: 10px;
}

.section-title {
  font-size: 1.2rem;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.section-subtitle {
  font-weight: bold;
  margin-bottom: 10px;
  color: #606266;
}

.homework-content {
  margin-bottom: 20px;
}

.content {
  line-height: 1.6;
  white-space: pre-wrap;
}

.attachment-section {
  margin-top: 20px;
}

.submission-section {
  margin-top: 20px;
}

.submission-info {
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.submission-time {
  color: #909399;
  margin-bottom: 15px;
}

.submission-content {
  margin-bottom: 20px;
}

.submission-attachment {
  margin-bottom: 20px;
}

.submission-actions {
  margin-top: 20px;
}

.feedback-section {
  margin-top: 20px;
}

.feedback-info {
  padding: 15px;
  background-color: #f0f9eb;
  border-radius: 4px;
}

.score {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.score-label {
  font-weight: bold;
  margin-right: 10px;
}

.score-value {
  font-size: 24px;
  color: #409EFF;
  font-weight: bold;
}

.feedback-comment {
  margin-top: 15px;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
</style> 